var fs      = require( 'fs' ),
path        = require( 'path' ),
url         = require( 'url' ),
util        = require( 'util' ),
querystring = require( 'querystring' ),
logger      = require( 'morgan' ),
bodyParser  = require( 'body-parser' ),
session     = require( 'express-session' ),
cookie      = require( 'cookie-parser' ),
Dir         = path.parse( __dirname ).dir,
ctrlDir     = Dir + '/controller';

module.exports = function( options ){
    
    options.session = session;
    options.cookie  = cookie;
    
    var express = options.express,
    router      = options.express.Router(),
    app         = options.app,
    Config      = app.get('config'),
    psfx        = Config.psfx;
    
    // logs
    Config.logger && app.use( logger() );
    
    // session
    app.use(session({
        secret: Config.secret, //secret的值
        cookie: {maxAge: 60 * 1000 * Config.sessionOutTime} // 过期时间（毫秒）
    }));
    
    // post 请求 获取参数模块
    app.use(bodyParser.urlencoded({ extended: false }));
    app.use(bodyParser.json());
    
    // proxy封装处理, 一般要求都能满足, 如果想用高级配置请用originProxy方法, 如果这个方法还不行可以用helper里面的turnHost
    options.proxy = function( uri, turnUri, async ){
        
        if( !( typeof uri=='string' && uri ) ){new Error('请传入uri必选参!');}
        if( !( typeof turnUri=='string' && turnUri ) ){
            turnUri = uri;
        }
        
        if( turnUri.indexOf('http')==-1 ){
            if( Config.turnHost.indexOf('http')==-1 ){new Error('请在config文件正确配置turnHost参数信息!')}
            turnUri = Config.turnHost + turnUri;
        }
        
        turnUri = turnUri.replace(/\/+/g, '/').replace(/(https?:\/)/, '$1/');
        
        app.use( uri, function( request, response, next ){
            querystring.stringify( request.query );
            var iproxy = options.originProxy( url.parse(turnUri).hostname, {
                forwardPath: function(req, res){
                    return ( turnUri + ( turnUri.indexOf('?')>-1 ? '&' : '?' ) + querystring.stringify( request.query ) ).replace(/\?$/,'');
                },
                port: url.parse(turnUri).port,
                // 是否以Buffer的形式返回
                reqAsBuffer: false,
                // 是否打印日志
                logger: Config.logger,
                // 是否异步, 一般情况用异步
                async: async
            })( request, response, next );
        });
        return app;
    }
    
    // application 主控制器
    require( ctrlDir + '/application' )( options );
    
    // 当前目录所有路由文件
    var routes = fs.readdirSync( ctrlDir ),
    doDB       = require('../core/do_mysql');
    
    routes.forEach(function( file ){
        
        if( path.extname( file )==='.js' && file!=='application.js' ){
            
            var pathname = ctrlDir +'/' + file;
            // model检测 考虑文件也比较小就用try
            //fs.stat()// 文件信息检查 fs.access 在非windows系统中对文件权限的检查
            try{
                options.Model = require( '../model/'+file )( options, doDB )||null;
            }catch(e){
                options.Model = null;
            }finally{
                
            }
            
            require( pathname )( options );
            
        }
        
    })
    
    
    app.get('*', function( request, response ){
        
        response.status( 404 );
        response.render( 'error/404', {
            title: '您访问的页面不存在',
            layout: app.locals.layout
        });
        
    })
    
    
}